package com.jzg.sys.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzg.sys.common.rest.BaseRest;
import com.jzg.sys.common.vo.ResultVO;
import com.jzg.sys.dao.entity.SecRole;
import com.jzg.sys.dao.entity.SecUser;
import com.jzg.sys.manager.SecRoleManager;
import com.jzg.sys.manager.SecUserManager;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping(value = "/userAction")
public class UserAction extends BaseRest {
	@Autowired
	private SecUserManager secUserManager;

	@RequestMapping(value = "/findEasyPage")
	@ResponseBody
	public IPage findEasyPage(Page<SecUser> easyPage, SecUser secUser) {
		return secUserManager.findEasyPage(easyPage, secUser);
	}

	@RequestMapping(value = "/findById")
	@ResponseBody
	public SecUser findById(String id) {
		return secUserManager.getById(id);
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public ResultVO save(SecUser secUser) {
		ResultVO vo = new ResultVO();
		try {
			if(StringUtils.startsWith(secUser.getUserId(), "new")){
				secUser.setUserId(secUser.getUserId().replaceFirst("new", ""));
				secUser.setPassword(DigestUtils.md5Hex("123456"));
				secUserManager.save(secUser);
			}else{
				secUserManager.updateById(secUser);
			}
		} catch (RuntimeException be) {
			be.printStackTrace();
			vo.setResult(false);
			vo.setMsg(be.getMessage());
			return vo;
		}
		return vo;
	}

	@RequestMapping(value = "/deleteUser")
	@ResponseBody
	public ResultVO deleteUser(String id) {
		ResultVO vo = new ResultVO();
		try {
			secUserManager.removeById(id);
		} catch (RuntimeException be) {
			be.printStackTrace();
			vo.setResult(false);
			vo.setMsg(be.getMessage());
			return vo;
		}
		return vo;
	}

	@RequestMapping(value = "/resetPassword")
	@ResponseBody
	public ResultVO resetPassword(String id) {
		ResultVO vo = new ResultVO();
		try {
			SecUser user = new SecUser();
			user.setUserId(id);
			user.setPassword(DigestUtils.md5Hex("123456"));
			secUserManager.updateById(user);
		} catch (RuntimeException be) {
			be.printStackTrace();
			vo.setResult(false);
			vo.setMsg(be.getMessage());
			return vo;
		}
		return vo;
	}

	@RequestMapping(value = "/updateStatus")
	@ResponseBody
	public ResultVO updateStatus(SecUser secUser) {
		ResultVO vo = new ResultVO();
		try {
			secUserManager.updateById(secUser);
		} catch (RuntimeException be) {
			be.printStackTrace();
			vo.setResult(false);
			vo.setMsg(be.getMessage());
			return vo;
		}
		return vo;
	}
}
